jDcp.web.Table = function(){
	
	this.jTable = null;
	this.relativeTable = null;
	var _this = this;
	
	this.parse = function(htmlData){
		this.jTable = $(htmlData);
		this.attr("edit","true");
		
		//高亮主键
		var keys = this.attr("key");
		if(keys != null){
			var kk = keys.split(",");
			for ( var int = 0; int < kk.length; int++) {
				var k = kk[int];
				$.each(this.getTable().find("*[col='"+k+"']"),function(i,n){
					if(this.tagName == "TH") $(this).addClass("key");
					else {
						$(this).addClass("key-col");
						var sqltype = "";
						if(this.tagName == "TD") sqltype = $(this).parent().attr("sqltype");
						if(sqltype == "update") $(this).attr("readonly","readonly").addClass("disabled").attr("title","主键字段，在保存后不能编辑");
					}
				});
			}
		}
		
		//TODO: 添加事件
		if(this.jTable != null){
			
			//搜索栏显隐事件
			this.jTable.find(".filter-panel").find("legend").text("+ 搜索栏").nextAll().hide();
			this.jTable.find(".filter-panel").find("legend").click(function(){
				if($(this).next().find("label").length > 0){
					if($(this).text() == "- 搜索栏") $(this).text("+ 搜索栏");
					else $(this).text("- 搜索栏");
					$(this).nextAll().toggle();
				}
			});
			
			//搜索事件
			this.jTable.find(".filter-panel").find(".search-content").click(function(){
				var where = "";
				$.each(_this.jTable.find(".filter-panel").find("*[col]"),function(i,n){
					var value = $(this).val();
					if (value != null && value != "请下拉选择") {
						if(where != "") where += " AND ";
						where += $(this).attr("col") + "='" + value +"'";
					}
				});
				alert(where);
				var option = {};
				option.id = _this.attr("id");
				option.rand = Util.getRandom();
				option.action = "search";
				option.where = where;
				$.post("/DCP3/jTable",option,function(data){
					alert(data);
				});
			});
			
			//有下拉框的单元格居中
			this.jTable.find("td:has(select)").addClass("stay-center");
			
			//点击行序号时切换选中状态
			$("td.th").live('click',function(){
				_this.jTable.find("tr").not($(this).parent()).removeClass("currentrow");
				$(this).parent().toggleClass("info").toggleClass("currentrow");
			});
			
			//所有有下拉框的单元格，下拉值变化事件
			$("td.td").find("select").live("change",function(){
				var td = $(this).parent();
				var nv = $(this).val();
				var ov = td.attr("ov");
				if(nv != ov) {
					td.addClass("warning");
				}else{
					td.removeClass("warning");
				}
			});
			
			//单元格编辑事件
			$("td.td").live('dblclick',function(e){
				if(_this.attr("edit") == "false") return;
				var td = $(this);
				Util.edit(td);
				e.preventDefault();
				return false;
			}).live("click",function(e){
				var td = $(this);
				$("#rightMenu").remove();
				$(".last-focus").removeClass("last-focus");
				td.addClass("last-focus");
				if(td.find(".edit-cell").length == 0) Util.removeWorking();
				$(".info").removeClass("info");
				td.parent().addClass("info");
				e.preventDefault();
				return false;
			});
			
			$("button.search-btn").live('click',function(){
				alert(123);
			});
			
			//标题事件
			this.getTable().find("tr.jtable-title").find("th").click(function(e){
				$("#rightMenu").remove();
				var col = $(this).attr("col");
				var htmlTemplate =  " <div colindex='"+$(this).index()+"' class='dropdown' id='rightMenu' style='position: absolute;'><ul class='dropdown-menu' role='menu' aria-labelledby='dropdownMenu'> "+
									"   <li><a tabindex='-1' href='#'><i class='icon-arrow-up'></i> 排序 A-Z</a></li> "+
									"   <li><a tabindex='-1' href='#'><i class='icon-arrow-down'></i> 排序 Z-A</a></li> "+
									"   <li class='divider'></li> "+
									"   <li><a tabindex='-1' href='#'><i class='icon-eye-open'></i> 显示隐藏项目</a></li> "+
									"   <li><a tabindex='-1' href='#'><i class='icon-eye-close'></i> 隐藏此列</a></li> "+
									"   <li><a tabindex='-1' href='#'><i class='icon-filter'></i> 过滤列</a></li> "+
									"   <li class='divider'></li> "+
									"   <li><a tabindex='-1' href='#'><i class='icon-font'></i> 统一设值</a></li> "+
									"   <li><a tabindex='-1' href='#'><i class='icon-zoom-in'></i> 设为查询条件</a></li> "+
									"   <li class='divider'></li> "+
									"   <li class='disabled'><a tabindex='-1' href='#'><b class='red'>字段：" + col + " { "+$(this).index()+" }</b></a></li> "+
									"   <li class='divider'></li> "+
									"   <li><a tabindex='-1' href='#'><i class='icon-remove'></i> 关闭</a></li> "+
									" </ul></div> ";
				var menu = $(htmlTemplate);
				menu.css({top:e.pageY,left:e.pageX}).appendTo($("body")).find(".dropdown-menu").show();
				
				//事件1：排序
				menu.find("li:has(i.icon-arrow-up)").click(function(){
					alert("up");
				}).end().find("li:has(i.icon-arrow-down)").click(function(){
					alert("down");
				}).end().find("li:has(i.icon-eye-open)").click(function(){
					_this.jTable.find("th:hidden").show();
					_this.jTable.find("td:hidden").show();
					menu.remove();
				}).end().find("li:has(i.icon-eye-close)").click(function(){
					var cols = menu.attr('colindex');
					$.each(_this.getTable().find("tr"),function(i,n){
						$(this).find("td:eq("+cols+")").hide();
						$(this).find("th:eq("+cols+")").hide();
					});
					menu.remove();
				}).end().find("li:has(i.icon-filter)").click(function(){
					var cols = window.prompt("请输入要隐藏的列号，点击标题栏即可查看当前列");
					alert(cols);
				}).end().find("li:has(i.icon-remove)").click(function(){
					menu.remove();
				});
			});
			
			//3. 按钮事件
			this.jTable.find("button.jtable-add").click(function(){
				var tr = null;
				if(_this.jTable.find("tr.info").length > 0){
					tr = _this.jTable.find("tr.info").clone(true);
				}else{
					tr = _this.jTable.find("tr:eq(1)").addClass("info").clone(true);
				}
				
				tr.attr("sqltype","insert").removeClass("info").find("td.th").text(_this.jTable.find("tr").length)
				  .end().find("*[readonly]").removeAttr("readonly")
				  .end().find("td").attr("ov","")
				  .addClass("warning")
				  .not(":first").not(":has(select)").not(".key-col").text("");
//				tr.find("td").not(":first").filter(":has(select)").filter("td[key]").text("");
				_this.getTable().append(tr);
			}).end().find("button.jtable-save").click(function(){
				Util.removeWorking();
				var sqls = [];
				var key = _this.attr("key");
				var table = _this.attr("relativetable");
				$.each(_this.jTable.find("tr:has(td.warning)"),function(){
					$(this).find("td.th").addClass("success");
					var sqltype = $(this).attr("sqltype");
					if(sqltype == "insert"){
						sql = Util.getInsert($(this),table,key);
					}else{
						sql = Util.getUpdate($(this),table,key);
					}
					sqls.push(sql);
				});
				alert(sqls);
				var option = {};
				option.sqls = sqls.join("@");
				option.action = "runsql";
				option.rand = Util.getRandom();
				$.post("/DCP3/jTable",option,function(data){
					var sReturn = new String(data);
					if(sReturn.indexOf("成功") != -1){
						alert(sReturn);
						window.location.reload();
					}else{
						alert(sReturn);
					}
				});
			}).end().find("button.jtable-delete").click(function(){
				if(!confirm("删除确认\n\n是否要删除界面中淡蓝底色数据??")) return;
				var sqls = [];
				var key = _this.attr("key");
				var table = _this.attr("relativetable");
				$.each(_this.getSelectRows(),function(i,n){
					var sql = Util.getDelete($(this),table,key);
					sqls.push(sql);
				});
				var option = {};
				option.sqls = sqls.join("@");
				option.action = "runsql";
				option.rand = Util.getRandom();
				$.post("/DCP3/jTable",option,function(data){
					var sReturn = new String(data);
					if(sReturn.indexOf("成功") != -1){
						alert(sReturn);
						window.location.reload();
					}
				});
			});
		}
	};
	
	//************************************与值相关函数*****************************************//
	/**
	 * 获取某一行的字段值，从第1行开始。
	 */
	this.getColValue = function(col,row){
		return _this.getTable().find("tr:eq("+row+")").find("td[col='"+col+"']").text().trim();
	};
	
	this.getColValues = function(col){
		var reArray = _this.getTable().find("tr").not(":first").map(function(i,n){
			return $(this).find("td[col='"+col+"']").text().trim();
		}).get();
		return reArray;
	};
	
	/**
	 * 设置当前行的某字段的字段值
	 * */
	this.setColValueAtCurrentRow = function(td,col,value){
		td.parent().find("td[col='"+col+"']").text(value);
	};
	
	/**
	 * 设置当前行的某字段的字段值,指定行号，与字段名
	 * */
	this.setColValue = function(col,row,value){
		_this.getTable().find("tr:eq("+row+")").find("td[col='"+col+"']").text(value).attr("oldvalue",value);
	};
	
	/**
	 * 隐藏某些列不显示
	 */
	this.hideCols = function(obj){
		if(obj != null){
			var col = obj.col;
			if(col != null){
				var cc = col.split(",");
				for(var i = 0;i < cc.length;i ++){
					$.each(_this.getTable().find("th[col='"+cc[i]+"']"),function(i,n){
						$(this).hide();
					});
					$.each(_this.getTable().find("td[col='"+cc[i]+"']"),function(i,n){
						$(this).hide();
					});
				}
			}
			var index = obj.index;
			if(index != null){
				var ii = index.split(",");
				for(var j = 0;j < ii.length;j ++){
					var k = new Number(ii[j]);
					$.each(_this.getTable().find("tr"),function(i,n){
						$(this).find("td:eq("+k+")").hide();
						$(this).find("th:eq("+k+")").hide();
					});
				}
			}
		}
	};
	
	this.hideModelRow = function(title){
		if(_this.getTable().find("tr[sqltype='update']").length == 0){
			var tr = $("<tr class='info'><td class='stay-center' colspan='" + _this.getRow(1).find("td").length + "'>"+title+"</td></tr>");
			_this.getRow(1).remove();
			_this.addRow(tr);
		};
	};
	
	this.addRow = function(row){
		_this.getTable().append(row);
	};
	
	this.getRow = function(rowIndex){
		return this.jTable.find("tr:eq('"+rowIndex+"')");
	};
	
	this.getCurrentRow = function(){
		return this.jTable.find("tr.currentrow");
	};
	
	this.getSelectRows = function(){
		return this.jTable.find("tr.info");
	};
	
	this.getTable = function(){
		return _this.jTable.find(".jtable");
	};
	
	this.attr = function(name,value){
		if(value == null){
			return _this.getTable().attr(name); 
		}else{
			_this.getTable().attr(name,value);
		}
	};
	//************************************与值相关函数*****************************************//
	
	this.getRowCount = function(){
		return this.getTable().find("tr").length - 1;
	};
	
	this.hideButton = function(str){
		_this.jTable.find(".jtable-buttons").find(str).remove();
	};
	
	this.setEdit = function(bool){
		_this.getTable().attr("edit",bool);
		if(!bool) _this.getTable().find("select").attr("disabled","disabled");
	};
	
	this.appendTo = function(id){
		var container = "#" + id;
		$(container).append(this.jTable);
	};
	
	this.addButton = function(option){
		var _default = {
			cls:"btn",
			img:"icon-circle-arrow-right",
			text:"未命名按钮",
			title:"这是一个自定义的按钮",
			fn:function(){alert("请指定一个按钮事件 ! \n\noption.fn = function(){\n...\n}");}
		};
		var setting = $.extend({},_default,option);
		var button = $("<button class='btn mr5 "+setting.cls+"' title='"+setting.title+"'><i class='"+setting.img+"'></i> "+setting.text+"</button>");
		button.bind('click',setting.fn);
		this.jTable.find("div.jtable-buttons").append(button);
	};
	
	this.insertCol = function(tdHTML,title,index){
		var td = $(tdHTML);
		$.each(_this.getTable().find("tr"),function(i,n){
			if(i == 0) {
				var html = "<th class='stay-center th'>"+title+"</th>";
				$(html).insertAfter($(this).find("th:eq('"+index+"')"));
			}
			td.clone().insertAfter($(this).find("td:eq('"+index+"')"));
		});
	};
	
	this.setRowClass = function(index,cls){
		_this.getTable().find("tr:eq('"+index+"')").find("td.th").addClass(cls);
	};
};

jDcp.web.Table.BUTTON_ADD = ".jtable-add";
jDcp.web.Table.BUTTON_SAVE = ".jtable-save";
jDcp.web.Table.BUTTON_DELETE = ".jtable-delete";